package com.shycloud.mido.member.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.member.api.entity.SmMemberGroupStudent;
import com.shycloud.mido.member.mapper.SmMemberGroupStudentMapper;
import com.shycloud.mido.member.service.SmMemberGroupStudentService;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class SmMemberGroupStudentServiceImpl extends ServiceImpl<SmMemberGroupStudentMapper, SmMemberGroupStudent> implements SmMemberGroupStudentService {

	/** 教师分组下学生 mapper */
	private SmMemberGroupStudentMapper memberGroupStudentMapper;

	/**
	 * 批量添加学生进分组
	 *
	 * @param studentIdArr
	 * @param groupId
	 * @return boolean
	 * @author nianhua.jiang
	 * @date 2020/6/22 13:43
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public boolean addStudentList(List<String> studentIdArr, Integer groupId) {

		//批量添加学生进分组
		for (String studentId : studentIdArr) {

// 			SmMemberGroupStudent smMemberGroupStudent = memberGroupStudentMapper.selectOne(new QueryWrapper<SmMemberGroupStudent>()
//					.eq(SmMemberGroupStudent.COL_STUDENT_ID, studentId)
//					.and(x -> x.eq(SmMemberGroupStudent.COL_GROUP_ID, groupId)));
//
//			if (smMemberGroupStudent != null || (smMemberGroupStudent == null && groupId == -1)) {
//				throw new BusinessException("您的学生已在该分组中");
//			}

			//首先将该学生从分组中移除
			memberGroupStudentMapper.delete(new QueryWrapper<SmMemberGroupStudent>()
					.eq(SmMemberGroupStudent.COL_STUDENT_ID, studentId));

			if (groupId != -1) {
				//创建对象
				SmMemberGroupStudent groupStudent = new SmMemberGroupStudent();
				//创建时间
				groupStudent.setCreateTime(new Date());
				//分组ID
				groupStudent.setGroupId(groupId);
				//学生ID
				groupStudent.setStudentId(studentId);
				//添加学生进分组
				memberGroupStudentMapper.insert(groupStudent);
			}

		}
		return true;
	}

	/**
	 * 从分组中批量移除学生
	 *
	 * @param studentIdArr
	 * @param groupId
	 * @return boolean
	 * @author nianhua.jiang
	 * @date 2020/6/22 15:14
	 */
	@Override
	public boolean removeStudentList(List<String> studentIdArr, Integer groupId) {

		//循环删除
		for (String studentId : studentIdArr) {
			SmMemberGroupStudent smMemberGroupStudent = memberGroupStudentMapper.selectOne(new QueryWrapper<SmMemberGroupStudent>()
					.eq(SmMemberGroupStudent.COL_GROUP_ID, groupId)
					.and(x -> x.eq(SmMemberGroupStudent.COL_STUDENT_ID, studentId)));
			memberGroupStudentMapper.deleteById(smMemberGroupStudent.getId());
		}
		return true;
	}
}
